<template>
  <div class="container">
    <img :src="image" ref="imgRef">
    <van-nav-bar left-text="返回" right-text="确定" @click-left="$emit('close')" @click-right="onConfirm" />
  </div>
</template>

<script>
import { updateUserPhoto } from '@/api/user.js'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
  props: {
    file: {
      required: true
    }
  },
  data() {
    return {
      image: window.URL.createObjectURL(this.file),
      cropper: null
    }
  },
  mounted() {
    this.cropper = new Cropper(this.$refs.imgRef, {
      aspectRatio: 1,
      viewMode: 1,
      dragMode: 'move',
      background: false,
      movable: true,
      cropBoxMovable: false,
      cropBoxResizable: false
    })
  },
  methods: {
    getCroppedCanvas() {
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob(file => {
          resolve(file)
        })
      })
    },
    async onConfirm() {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true
      })
      const blod = await this.getCroppedCanvas()
      const fd = new FormData()
      fd.append('photo', blod)
      await updateUserPhoto(fd)
      this.$emit('photo', window.URL.createObjectURL(blod))
      this.$emit('close')
      this.$toast.success('保存成功！')
    }
  }
}
</script>
<style lang="less" scoped>
.container {
  background: rgba(0, 0, 0, 0.7);
  height: 100%;
  img {
    width: 100%;
    display: block;
  }
}
.van-nav-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  background-color: unset;

  // opacity: 0.1;
  width: 100%;
  .van-nav-bar__text {
    color: #333;
  }
}
</style>
